/*
 * @Author: Wangjun
 * @Date: 2023-03-15 13:32:52
 * @LastEditTime: 2023-09-02 17:23:38
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \golib\js\jsutil\model.go
 * hnxr
 */
package jsutil

import (
	"os"
	"time"

	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/libs/easy"
	"github.com/dop251/goja"
)

// YYYY/MM/DD HH:mm:ss
// 初始化js需要的组件
func InitModels(vm *goja.Runtime) {
	//注册console组件
	stacks := make([]goja.StackFrame, 2)
	console := vm.NewObject()
	stack := func() string {
		ss := vm.CaptureCallStack(2, stacks)
		i := len(ss) - 1
		if i < 0 {
			return ""
		}
		return "file:" + ss[i].Position().String() + ",function:" + ss[i].FuncName() + " "
	}
	console.Set("trace", func(v ...interface{}) {
		logs.LiteDebug(stack(), v...)
	})
	console.Set("log", func(v ...interface{}) {
		logs.LiteInfo(stack(), v...)
	})
	console.Set("info", func(v ...interface{}) {
		logs.LiteInfo(stack(), v...)
	})
	console.Set("warn", func(v ...interface{}) {
		logs.LiteWarn(stack(), v...)
	})
	console.Set("error", func(v ...interface{}) {
		logs.LiteError(stack(), v...)
	})
	vm.Set("console", console)

	vm.Set("load", func(name string) goja.Value {
		data, err := os.ReadFile(name)
		if err != nil {
			vm.Interrupt(err)
			return nil
		}
		_, err = vm.RunScript(name, string(data))
		if err != nil {
			vm.Interrupt(err)
			return nil
		}

		return vm.Get("model")
	})

	//2006-01-02 15:04:05.999
	//注册时间组件, 后续进行优化
	fecha := vm.NewObject()
	fecha.Set("format", func(x time.Time, fmt string) string {
		return x.Format(easy.ConvertFormat(fmt))
	})

	vm.Set("fecha", fecha)
}
